package com.shop.cereshop.app.service.report.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.report.CereReportRecordDAO;
import com.shop.cereshop.app.dao.recommend.CereRecommendTrendsDAO;
import com.shop.cereshop.app.dao.recommend.CereRecommendCommentDAO;
import com.shop.cereshop.app.dao.buyer.CereBuyerUserDAO;
import com.shop.cereshop.app.page.recommend.CereRecommendCommentPageVO;
import com.shop.cereshop.app.page.report.ReportRecordVO;
import com.shop.cereshop.app.param.report.ReportPageDTO;
import com.shop.cereshop.app.param.report.MyReportPageDTO;
import com.shop.cereshop.app.service.report.CereReportRecordService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.report.CereReportRecord;
import com.shop.cereshop.commons.domain.report.dto.ReportSubmitDTO;
import com.shop.cereshop.commons.domain.recommend.CereRecommendTrends;
import com.shop.cereshop.commons.domain.recommend.CereRecommendComment;
import com.shop.cereshop.commons.enums.report.ReportStatusEnum;
import com.shop.cereshop.commons.enums.report.ReportTargetTypeEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 举报记录服务实现类
 *
 * @author
 */
@Service
@Slf4j
public class CereReportRecordServiceImpl implements CereReportRecordService {

    @Autowired
    private CereReportRecordDAO cereReportRecordDAO;

    @Autowired
    private CereRecommendTrendsDAO cereRecommendTrendsDAO;

    @Autowired
    private CereRecommendCommentDAO cereRecommendCommentDAO;

    @Autowired
    private CereBuyerUserDAO cereBuyerUserDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitReport(ReportSubmitDTO param, CereBuyerUser user) throws CoBusinessException {
        // 参数校验已在Controller层通过@Validated注解完成
        //当TargetType 等于4 isIM等于1 是im举报管理
        if (param.getTargetType() == 4 && param.getIsIM() == 1) {

        }
        // 根据目标类型和目标ID查询对应的内容，获取被举报人ID
        Long reportedUserId = getReportedUserId(param.getTargetType(), param.getTargetId());
        if (reportedUserId == null) {
            throw new CoBusinessException(CoReturnFormat.FAIL, "举报目标不存在");
        }

        // 不能举报自己
        if (reportedUserId.equals(user.getBuyerUserId())) {
            throw new CoBusinessException(CoReturnFormat.FAIL, "不能举报自己");
        }

        // 检查是否已举报
        CereReportRecord existingReport = cereReportRecordDAO.getReportByUserAndTarget(
                user.getBuyerUserId(), param.getTargetType(), param.getTargetId());
        if (existingReport != null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_ALREADY_EXISTS);
        }

        // 创建举报记录
        CereReportRecord reportRecord = new CereReportRecord();
        BeanUtil.copyProperties(param, reportRecord);
        reportRecord.setReporterUserId(user.getBuyerUserId());
        reportRecord.setReportedUserId(reportedUserId);
        reportRecord.setReportStatus(ReportStatusEnum.PENDING.getCode());

        // 处理举报图片
        if (CollectionUtil.isNotEmpty(param.getReportImages())) {
            reportRecord.setReportImages(String.join(",", param.getReportImages()));
        }

        String now = TimeUtils.yyMMddHHmmss();
        reportRecord.setCreateTime(now);
        reportRecord.setUpdateTime(now);

        // 保存举报记录
        int result = cereReportRecordDAO.insert(reportRecord);
        if (result <= 0) {
            throw new CoBusinessException(CoReturnFormat.FAIL);
        }

        log.info("用户{}举报成功，举报ID：{}", user.getBuyerUserId(), reportRecord.getReportId());
        return reportRecord.getReportId();
    }

    @Override
    public Page<ReportRecordVO> getReportPage(ReportPageDTO param, CereBuyerUser user) throws CoBusinessException {
        // 设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());

        // 查询举报记录
        List<ReportRecordVO> list = cereReportRecordDAO.getReportPage(param);
        PageInfo<ReportRecordVO> pageInfo = new PageInfo<>(list);

        return new Page<>(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public ReportRecordVO getReportDetail(Long reportId, CereBuyerUser user) throws CoBusinessException {
        // 参数校验已在Controller层通过@NotNull注解完成

        // 查询举报详情
        CereReportRecord reportRecord = cereReportRecordDAO.selectById(reportId);
        if (reportRecord == null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_NOT_EXISTS);
        }

        // 检查权限：只有举报人才能查看详情
        if (!reportRecord.getReporterUserId().equals(user.getBuyerUserId())) {
            throw new CoBusinessException(CoReturnFormat.NO_PERMISSION);
        }

        // 转换为VO
        ReportRecordVO vo = new ReportRecordVO();
        BeanUtil.copyProperties(reportRecord, vo);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelReport(Long reportId, CereBuyerUser user) throws CoBusinessException {
        // 参数校验已在Controller层通过@NotNull注解完成

        // 查询举报记录
        CereReportRecord reportRecord = cereReportRecordDAO.selectById(reportId);
        if (reportRecord == null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_NOT_EXISTS);
        }

        // 检查权限：只有举报人才能撤销
        if (!reportRecord.getReporterUserId().equals(user.getBuyerUserId())) {
            throw new CoBusinessException(CoReturnFormat.NO_PERMISSION);
        }

        // 检查状态：只有待审核状态才能撤销
        if (!ReportStatusEnum.PENDING.getCode().equals(reportRecord.getReportStatus())) {
            throw new CoBusinessException(CoReturnFormat.REPORT_CANNOT_CANCEL);
        }

        // 删除举报记录
        int result = cereReportRecordDAO.deleteById(reportId);
        if (result <= 0) {
            throw new CoBusinessException(CoReturnFormat.FAIL);
        }

        log.info("用户{}撤销举报成功，举报ID：{}", user.getBuyerUserId(), reportId);
        return true;
    }

    @Override
    public Boolean hasReported(Integer targetType, Long targetId, CereBuyerUser user) {
        if (user == null) {
            return false;
        }

        CereReportRecord reportRecord = cereReportRecordDAO.getReportByUserAndTarget(
                user.getBuyerUserId(), targetType, targetId);
        return reportRecord != null;
    }

    @Override
    public Page<ReportRecordVO> getMyReports(MyReportPageDTO param, CereBuyerUser user) throws CoBusinessException {
        // 创建查询参数，只包含需要的字段
        ReportPageDTO queryParam = new ReportPageDTO();
        queryParam.setReporterUserId(user.getBuyerUserId());
        queryParam.setReportStatus(param.getReportStatus());
        queryParam.setReportTypeId(param.getReportTypeId());
        queryParam.setStartTime(param.getStartTime());
        queryParam.setEndTime(param.getEndTime());
        queryParam.setPage(param.getPage());
        queryParam.setPageSize(param.getPageSize());

        // 设置分页参数
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());

        // 查询我的举报记录
        List<ReportRecordVO> list = cereReportRecordDAO.getReportPage(queryParam);
        PageInfo<ReportRecordVO> pageInfo = new PageInfo<>(list);

        return new Page<>(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Object getReportStats(CereBuyerUser user) {
        // 统计举报数量
        Integer reportCount = cereReportRecordDAO.countUserReports(user.getBuyerUserId());

        // 统计被举报数量
        Integer reportedCount = cereReportRecordDAO.countReportedByUser(user.getBuyerUserId());

        Map<String, Object> stats = new HashMap<>();
        stats.put("reportCount", reportCount);
        stats.put("reportedCount", reportedCount);

        return stats;
    }

    /**
     * 根据目标类型和目标ID获取被举报人用户ID
     *
     * @param targetType 目标类型
     * @param targetId   目标ID
     * @return 被举报人用户ID
     */
    private Long getReportedUserId(Integer targetType, Long targetId) {
        if (targetType == null || targetId == null) {
            return null;
        }
        try {
            if (ReportTargetTypeEnum.RECOMMEND.getCode().equals(targetType)) {
                // 动态类型：查询动态发布者
                CereRecommendTrends trends = cereRecommendTrendsDAO.selectById(targetId);
                return trends != null ? trends.getBuyerUserId() : null;

            } else if (ReportTargetTypeEnum.VIDEO.getCode().equals(targetType)) {
                // 视频类型：目前项目中视频可能也是动态的一部分，暂时按动态处理
                // 如果后续有独立的视频表，需要修改这里的逻辑
                CereRecommendTrends trends = cereRecommendTrendsDAO.selectById(targetId);
                return trends != null ? trends.getBuyerUserId() : null;

            } else if (ReportTargetTypeEnum.COMMENT.getCode().equals(targetType)) {
                // 评论类型：查询评论发布者
                CereRecommendCommentPageVO comment = cereRecommendCommentDAO.getCommentPageInfo(targetId);
                return comment != null ? comment.getUserId() : null;

            } else if (ReportTargetTypeEnum.USER.getCode().equals(targetType)) {
                // 用户类型：直接返回用户ID
                CereBuyerUser user = cereBuyerUserDAO.selectById(targetId);
                return user != null ? user.getBuyerUserId() : null;
            }
        } catch (Exception e) {
            log.error("获取被举报人用户ID失败，targetType: {}, targetId: {}", targetType, targetId, e);
        }

        return null;
    }
}
